<template>
  <CrudTable
    rowKey="index"
    :buttons="[]"
    row-selection-type="multiple"
    :columns="tableColumns"
    @currentChange="handleSelectChange"
    :tableData="pageData.tableData"
    :loading="pageData.loading"
    :showRefresh="true"
    :showExport="true"
    :hideEditInfo="true"
    :hideRemark="true"
    :hideRowSelect="true"
    @refreshData="handleTableRefresh"
  >
    <template #operations>
      <InputSelect
        :value="pageData.filterValue.customerMainName"
        @onClick="handleCustomerShow"
        placeholder="点击右侧按钮选择客户进行筛选..."
      />
      <t-space size="small">
        <t-button theme="primary" @click="filterChange">查询</t-button>
        <t-button theme="warning" @click="handleFilterReset">重置</t-button>
      </t-space>
    </template>
  </CrudTable>

  <SelectTable
    v-if="pageData.customer.show"
    :loading="pageData.customer.loading"
    :showDialog="pageData.customer.show"
    title="选择客户"
    width="60vw"
    rowSelectionType="multiple"
    :tableData="pageData.customer.data.records"
    :columns="customerColumns"
    @onConfirm="handleCustomerConfirm"
    @onCancel="handleCustomerClose"
    :pagination="pageData.customer.pagination"
    :filter-value="pageData.customer.filterValue"
    @currentChange="handleCustomerSelectChange"
    @filter-change="handleCustomerFilterChange"
    @page-change="handleCustomerPageChange"
    :zIndex="2600"
  />
</template>

<script lang="tsx" setup>
// 框架和组件库
import { reactive } from "vue";

// TS 类型文件
import type { ICrudTableDataPage, ISelectTableGroups } from "@/types";

// 工具函数
import { http } from "@/utils/fetch";
import { getValueBySelectData, newPrecision } from "@/utils/tools";

// 常量
import { CURRENCY_LIST, PAGINATION_VALUE } from "@/common/constants";

// API
import { getCustomerList } from "@/api/cas";

// 业务数据
import { tableColumns } from "./columns";
import { tableColumns as customerColumns } from "@/pages/Dashboard/CAS/Customer/components/columns";

// 动态组件
// const EditForm = defineAsyncComponent(() => import("./components/EditForm.vue"));

const GET_LIST_PATH = "/customer/credit/export"; // 查询信息接口
// const DELETE_ITEM_PATH = "/order/delete"; // 删除接口

const pageData = reactive({
  loading: false,
  tableData: [],
  selectedRow: {} as Record<string, any>,
  selectedRowsEvent: {} as Record<string, any>,
  selectedRowId: "",
  showEditForm: false,
  editFormMode: "",
  showApplyRePay: false,
  filterValue: {
    customerMainName: "",
    customerIds: []
  },
  customer: {
    show: false,
    loading: false,
    data: {} as ICrudTableDataPage,
    pagination: {
      pageSize: 20,
      total: 0,
      current: 1
    },
    filterValue: {}
  } as ISelectTableGroups
});

// 表格操作按钮配置
// const tableButtons = computed(() => [
//   {
//     name: "新增",
//     click: () => {
//       handleOperateRow("new");
//     }
//   }
// ]);

// 获取列表数据
const findAllList = async () => {
  pageData.loading = true;
  const resultData = await http("POST", GET_LIST_PATH, pageData.filterValue);
  if (resultData.code === 200) {
    /* 为什么这里我会用 map 处理一下数据，而不是用 TDesign 的 cell，
     * 是因为导出功能针对 TDesign 的 cell 无效，我也不想再修改公共方法了，
     * 不如 .map 处理一下省事。
     */
    pageData.tableData = resultData.data.map((item: Record<string, any>, index: number) => {
      return {
        index,
        ...item,
        balance: newPrecision(item.balance, 2),
        used: newPrecision(item.used, 2),
        amount: newPrecision(item.amount, 2),
        type: getValueBySelectData(CURRENCY_LIST, item.type)
      };
    });
    // pageData.pagination.total = resultData.data.total;
    // pageData.pagination.current = resultData.data.current;
    // pageData.pagination.pageSize = resultData.data.size;
    pageData.loading = false;
  }
};

// 获取客户选择列表的方法
const handleCustomerShow = () => {
  pageData.customer.show = true;
  getCustomerData();
};

const getCustomerData = async () => {
  pageData.customer.loading = true;
  const resultData = await getCustomerList(
    pageData.customer.pagination.current,
    pageData.customer.pagination.pageSize,
    pageData.customer.filterValue
  );

  if (resultData.code === 200) {
    pageData.customer.data = resultData.data;
    pageData.customer.pagination.total = resultData.data.total;
    pageData.customer.pagination.current = resultData.data.current;
    pageData.customer.pagination.pageSize = resultData.data.size;
    pageData.customer.loading = false;
  }
};

const handleCustomerPageChange = (pageInfo: Record<string, any>) => {
  pageData.customer.pagination.pageSize = pageInfo.pageSize;
  pageData.customer.pagination.current = pageInfo.current;
  getCustomerData();
};

const handleCustomerFilterChange = (filters: Record<string, any>) => {
  pageData.customer.filterValue = filters;
  pageData.customer.pagination = structuredClone(PAGINATION_VALUE);
  getCustomerData();
};

const handleCustomerSelectChange = (e: Record<string, any>) => {
  pageData.filterValue.customerIds = e.keys;

  // 设置这个函数的目的是为了及时更新数据，免得被误判为“属于已经选中过数据，但是点击选择列表之后没有做出改动”的情况。
  if (e.keys.length === 0) {
    pageData.filterValue.customerMainName = "";
  } else {
    pageData.filterValue.customerMainName = `已选中 “${e.options.selectedRowData[0].name}”等 ${e.keys.length} 个`;
  }
};

const handleCustomerConfirm = () => {
  pageData.customer.show = false;
};

const handleCustomerClose = () => {
  pageData.customer.show = false;
};

// 过滤事件触发函数
const filterChange = () => {
  findAllList();
};

const handleFilterReset = () => {
  pageData.filterValue = { customerMainName: "", customerIds: [] };
  findAllList();
};

const handleTableRefresh = () => {
  pageData.selectedRow = {};
  pageData.selectedRowId = "";
  pageData.filterValue = { customerMainName: "", customerIds: [] };
  findAllList();
};

// const handleRowDbClick = (context: Record<string, any>) => {
//   handleOperateRow("view", context.row);
// };

// const handleOperateRow = (mode: string, row?: Record<string, any>) => {
//   if (mode !== "delete") {
//     if (mode === "new") {
//       pageData.selectedRow = {};
//       pageData.selectedRowId = "";
//     } else {
//       pageData.selectedRow = row!;
//       pageData.selectedRowId = row!.id;
//     }
//     pageData.editFormMode = mode;
//     pageData.showEditForm = true;
//   } else if (mode === "delete") {
//     const confirmDialog = DialogPlugin({
//       header: "警告",
//       body: "确定要删除这一条数据吗？",
//       confirmBtn: "确定",
//       cancelBtn: "取消",
//       onConfirm: async () => {
//         const deleteData = await http("DELETE", `${DELETE_ITEM_PATH}?id=${row!.id}`);
//         if (deleteData.code === 200) {
//           MessagePlugin.success("删除成功！");
//           findAllList();
//           confirmDialog.hide();
//         }
//       },
//       onClose: () => {
//         confirmDialog.hide();
//       }
//     });
//   } else {
//     MessagePlugin.error("错误：未知的表格操作模式。");
//   }
// };

const handleSelectChange = (e: Record<string, any>) => {
  pageData.selectedRowsEvent = e;
};

findAllList();
</script>
